package com.ls.herostory.session;

import com.ls.herostory.login.User;
import com.ls.herostory.msg.GameMsgProtocol;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author liangsu
 * @version v1.0
 * @Description
 * @Date 2020/10/12 9:36
 * @since
 */
public class SessionUtil {

    private static ConcurrentHashMap<NioSocketChannel, Integer> channelToUserId = new ConcurrentHashMap<>();

    private static ConcurrentHashMap<Integer, Session> userIdT0Session = new ConcurrentHashMap<>();

    private static ConcurrentHashMap<Integer, NioSocketChannel> userIdToChannel = new ConcurrentHashMap<>();

    public static void createSession(User cmd, NioSocketChannel channel){
        Session session = userIdT0Session.get(cmd.getId());
        if(session == null){
            session = new Session();
            session.setUserId(cmd.getId());
            session.setUserName(cmd.getUserName());
            session.setHeroAvatar(cmd.getHeroAvatar());
            session.setChannel(channel);
            userIdT0Session.put(cmd.getId(), session);
        }

        channelToUserId.put(channel, cmd.getId());
        userIdToChannel.putIfAbsent(cmd.getId(), channel);
    }

    public static Session getSession(NioSocketChannel channel){
        Integer userId = channelToUserId.get(channel);
        if(userId != null){
            return userIdT0Session.get(userId);
        }
        return null;
    }

    public static Session getSession(Integer userId){
        return userIdT0Session.get(userId);
    }

    public static Session destorySession(NioSocketChannel channel){
        Integer userId = channelToUserId.remove(channel);

        // TODO: 2020/10/12
        if(userId != null){
            return userIdT0Session.remove(userId);
        }

        return null;
    }

    public static Collection<Session> getAllSession(){
        return userIdT0Session.values();
    }

}

